<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { loginByPasswordApi, loginByCodeApi, sendCodeApi } from '../../api/user';
import { useUserStore } from '../../stores/user';
import { ElMessage } from 'element-plus';
import { User, Lock, Message, Key, View, Hide } from '@element-plus/icons-vue';

const router = useRouter();
const mode = ref<'password' | 'code'>('password');
const email = ref('');
const password = ref('');
const code = ref('');
const loading = ref(false);
const showPassword = ref(false);
const userStore = useUserStore();

function validateEmail(email: string) {
  // 简单邮箱正则
  return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
}

function switchMode(newMode: 'password' | 'code') {
  mode.value = newMode;
  password.value = '';
  code.value = '';
}

async function sendCode() {
  if (!email.value) {
    ElMessage.error('请先填写邮箱！')
    return
  }
  if (!validateEmail(email.value)) {
    ElMessage.error('邮箱格式不正确！')
    return
  }
  loading.value = true;
  try {
    const res = await sendCodeApi(email.value);
    if (res.data && res.data.code === 200) {
      ElMessage.success('验证码已发送到邮箱！');
    } else {
      ElMessage.error(res.data.message || '验证码发送失败！');
    }
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '网络错误，验证码发送失败！');
  } finally {
    loading.value = false;
  }
}

async function login() {
  if (!email.value) {
    ElMessage.error('请填写邮箱！');
    return;
  }
  if (!validateEmail(email.value)) {
    ElMessage.error('邮箱格式不正确！');
    return;
  }
  if (mode.value === 'password') {
    if (!password.value) {
      ElMessage.error('请填写密码！');
      return;
    }
  } else {
    if (!code.value) {
      ElMessage.error('请填写验证码！');
      return;
    }
  }
  loading.value = true;
  try {
    let res;
    if (mode.value === 'password') {
      res = await loginByPasswordApi(email.value, password.value);
    } else {
      res = await loginByCodeApi(email.value, code.value);
    }
    if (res.code === 200) {
      // 登录成功，存储用户信息到store
      const userData = res.data || {};
      console.log(userData);
      userStore.id = userData.id || '';
      userStore.nickname = userData.nickname || '';
      userStore.gender = userData.gender || '';
      userStore.birthday = userData.birthday || '';
      userStore.bio = userData.personalIntroduce || '';
      userStore.email = email.value;
      userStore.avatar = userData.avatar || '';
      userStore.token = userData.token || '';
      
      ElMessage.success('登录成功！');
      router.push('/forumhome');
    } else {
      ElMessage.error(res.data.message || '登录失败！');
    }
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '网络错误，登录失败！');
  } finally {
    loading.value = false;
  }
}

onMounted(() => {
  // 检查用户是否已登录
  if (userStore.token) {
    ElMessage.info('您已登录，正在跳转...');
    router.push('/forumhome');
  }
});
</script>

<template>
  <div class="login-container">
    <div class="floating-shapes">
      <div class="shape shape-1"></div>
      <div class="shape shape-2"></div>
      <div class="shape shape-3"></div>
    </div>
    <div class="login-card">
      <div class="login-header">
        <div class="logo-container">
          <div class="logo-icon">
            <el-icon :size="40" color="#fff"><User /></el-icon>
          </div>
          <h2>课托邦登录</h2>
        </div>
      </div>
      <div class="login-tabs">
        <button :class="{active: mode==='password'}" @click="switchMode('password')">
          <el-icon class="tab-icon"><Lock /></el-icon>
          密码登录
        </button>
        <button :class="{active: mode==='code'}" @click="switchMode('code')">
          <el-icon class="tab-icon"><Message /></el-icon>
          验证码登录
        </button>
      </div>
      <form @submit.prevent="login">
        <div class="input-group">
          <div class="input-wrapper">
            <el-icon class="input-icon"><Message /></el-icon>
            <input v-model="email" type="email" placeholder="请输入邮箱" required />
          </div>
        </div>
        
        <div v-if="mode==='password'" class="input-group">
          <div class="input-wrapper">
            <el-icon class="input-icon"><Lock /></el-icon>
            <input 
              v-model="password" 
              :type="showPassword ? 'text' : 'password'" 
              placeholder="请输入密码" 
              required 
            />
            <el-icon class="password-toggle" @click="showPassword = !showPassword">
              <View v-if="!showPassword" />
              <Hide v-else />
            </el-icon>
          </div>
          <div class="forgot-container">
            <router-link to="/forgot" class="forgot-link">忘记密码？</router-link>
          </div>
        </div>
        
        <div v-else class="input-group">
          <div class="code-row">
            <div class="input-wrapper flex-1">
              <el-icon class="input-icon"><Key /></el-icon>
              <input v-model="code" type="text" placeholder="请输入验证码" required />
            </div>
            <button type="button" class="send-code" :disabled="loading" @click="sendCode">
              <el-icon class="btn-icon"><Message /></el-icon>
              发送验证码
            </button>
          </div>
        </div>
        
        <button class="login-btn" type="submit" :disabled="loading">
          <el-icon v-if="loading" class="loading-icon">
            <User />
          </el-icon>
          <span>{{ loading ? '登录中...' : '立即登录' }}</span>
        </button>
      </form>
      
      <div class="footer-links">
        <router-link to="/register" class="register-link">
          <el-icon class="link-icon"><User /></el-icon>
          没有账号？立即注册
        </router-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  min-width: 100vw;
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #a9c5f7 100%);
  z-index: 1000;
  overflow: hidden;
}

/* 浮动背景装饰 */
.floating-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
  animation: float 6s ease-in-out infinite;
}

.shape-1 {
  width: 80px;
  height: 80px;
  background: #fff;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.shape-2 {
  width: 120px;
  height: 120px;
  background: #e9ddfe;
  top: 20%;
  right: 10%;
  animation-delay: 2s;
}

.shape-3 {
  width: 60px;
  height: 60px;
  background: #a259ec;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(90, 80, 200, 0.2);
  padding: 48px 40px 40px 40px;
  min-width: 400px;
  max-width: 450px;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  position: relative;
  z-index: 10;
  border: 1px solid rgba(255, 255, 255, 0.2);
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  margin-bottom: 32px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  }
  50% {
    box-shadow: 0 4px 30px rgba(102, 126, 234, 0.5);
  }
  100% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  }
}

.login-card h2 {
  color: #333;
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-tabs {
  display: flex;
  margin-bottom: 32px;
  background: #f8faff;
  border-radius: 12px;
  padding: 4px;
  position: relative;
}

.login-tabs button {
  flex: 1;
  padding: 12px 16px;
  border: none;
  background: none;
  color: #666;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  position: relative;
  z-index: 2;
}

.tab-icon {
  font-size: 16px;
}

.login-tabs button:focus {
  outline: none;
}

.login-tabs button.active {
  color: #fff;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 16px;
  color: #999;
  font-size: 18px;
  z-index: 2;
}

.password-toggle {
  position: absolute;
  right: 16px;
  color: #999;
  font-size: 18px;
  cursor: pointer;
  z-index: 2;
  transition: color 0.2s;
}

.password-toggle:hover {
  color: #667eea;
}

input[type="email"],
input[type="password"],
input[type="text"] {
  padding: 16px 50px 16px 50px;
  border: 2px solid #eef2ff;
  border-radius: 12px;
  font-size: 16px;
  outline: none;
  transition: all 0.3s ease;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
}

input:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
}

.flex-1 {
  flex: 1;
}

.code-row {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.send-code {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 12px;
  padding: 16px 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.2);
}

.send-code:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
}

.send-code:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-icon {
  font-size: 16px;
}

.login-btn {
  margin-top: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 12px;
  padding: 16px 0;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.2);
}

.login-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 25px rgba(102, 126, 234, 0.3);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.loading-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.forgot-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 4px;
}

.forgot-link {
  color: #667eea;
  font-size: 13px;
  text-decoration: none;
  transition: all 0.2s;
  font-weight: 500;
}

.forgot-link:hover {
  color: #764ba2;
  text-decoration: underline;
}

.footer-links {
  margin-top: 24px;
  text-align: center;
}

.register-link {
  color: #667eea;
  font-size: 14px;
  text-decoration: none;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

.register-link:hover {
  color: #764ba2;
  text-decoration: underline;
}

.link-icon {
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-card {
    margin: 20px;
    padding: 32px 24px;
    min-width: auto;
    max-width: none;
  }
  
  .code-row {
    flex-direction: column;
    gap: 12px;
  }
  
  .send-code {
    width: 100%;
    justify-content: center;
  }
}
</style>
